﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Xml.Linq;
using System.ComponentModel;
using System.Threading;
using System.Collections.ObjectModel;

namespace TaxLawView
{
    public class Category : ILazy
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public int Depth { get; set; }
        private ObservableCollection<Category> _children = new ObservableCollection<Category>();
        public ObservableCollection<Category> Children
        {
            get
            {
                if (_isLoaded)
                    return _children;
                else
                    return new ObservableCollection<Category> { null };
            }
        }

        private bool _isLoaded = false;

        public bool IsLoaded
        {
            get { return _isLoaded; }
        }

        public void Load(Action complete)
        {
            BackgroundWorker bw = new BackgroundWorker();
            bw.WorkerReportsProgress = false;
            bw.WorkerSupportsCancellation = false;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += (sender, e) =>
                {
                    _isLoaded = true;
                    ObservableCollection<Category> result = e.Result as ObservableCollection<Category>;
                    if (result != null)
                    {
                        _children = result;
                    }
                    complete();
                };
            bw.RunWorkerAsync();
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = Service.GetCategories(this);
        }
    }
}
